<?php
namespace kernel\library;

/**
 * 环境变量获取
 *
 * @author 张启全
 *
 */
class Env
{
    
    /**
     *
     * @环境变量数据
     * @var array
     */
    protected static $data = [];
    
    /**
     *
     * @读取环境变量定义文件
     * @access public
     * @param string $file
     *            环境变量定义文件
     * @return void
     */
    public static function load(): void
    {
		$env = [];
        $env['BASICS_PATH'] = BASICS_PATH;
        $env['RUNTIME_PATH'] = BASICS_PATH . 'runtime' . DIRECTORY_SEPARATOR;
        $env['RESOURCES_PATH'] = BASICS_PATH . 'resources' . DIRECTORY_SEPARATOR;
        self::set($env);
    }
    
    /**
     *
     * @设置env
     */
    public static function set($env)
    {
        if (is_array($env)) {
            $env = array_change_key_case($env, CASE_UPPER);
            
            foreach ($env as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $k => $v) {
                        $k = 'BASICSPHP_' . $key . '_' . strtoupper($k);
                        self::$data[$k] = $v;
                        putenv("{$k}={$v}");
                    }
                } else {
                    $key = 'BASICSPHP_' . $key;
                    self::$data[$key] = $val;
                    putenv("{$key}={$val}");
                }
            }
        } else {
            $name = strtoupper(str_replace('.', '_', $env));
            $name = "BASICSPHP_" . $name;
            self::$data[$name] = $value;
        }
    }
    
    /**
     *
     * @获取env
     */
    public static function get($key, $default = '')
    {
        $key = 'BASICSPHP_' . $key;
        if (isset($_SERVER[$key])) {
            return $_SERVER[$key];
        } elseif (isset(self::$data[$key])) {
            return self::$data[$key];
        } else {
            return $default;
        }
    }
}


